using UnityEngine;

namespace GameCore
{
    public class PlaceWorldItemState : PlayerInputState
    {
        public WorldItem selected;
        public GridItem holding;
        public Cell cell;

        public PlaceWorldItemState(WorldItem item)
        {
            selected = item;
            holding = PrefabFactory.CreateInstance<GridItem>(item.resourceID);
            holding.SetData(item.GetData());
        }
        
        public override void OnHoveringCellChanged(Cell prev, Cell curr)
        {
            prev?.inventory.ClearPreview();
            curr?.inventory.PreviewPlaceItem(holding, curr.gridPos);
            cell = curr;
        }

        public override void Init(PlayerInputHandler handler)
        {
            selected.Select();
        }

        public override void Update()
        {
            var mousePos = PlayerInputHandler.GetMouseWorldPosition();
            holding.transform.position = new Vector3(mousePos.x - 0.5f, mousePos.y - 0.5f, -1);
            if (Input.GetMouseButtonDown(0))
            {
                if (cell is null) return;
                PlayerInputHandler.ApplyPlaceWorldItem();
            }
            else if (Input.GetMouseButtonDown(1))
            {
                PlayerInputHandler.CancelPlaceWorldItem();
            }
        }

        public override void Apply()
        {
            Object.Destroy(selected.gameObject);
            cell.PlaceItem(holding);
        }

        public override void Cancel()
        {
            Object.Destroy(holding.gameObject);
            selected.Deselect();
        }

        public override void Exit()
        {
            cell?.inventory.ClearPreview();
        }
    }
}